using System;
using System.Text.RegularExpressions;
using System.Configuration;
using Enterprise.URLRewriter.Config;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Web;

namespace Enterprise.URLRewriter
{
	/// <summary>
	/// Provides a rewriting HttpModule.
	/// </summary>
	public class ModuleRewriter : BaseModuleRewriter
	{
		/// <summary>
		/// This method is called during the module's BeginRequest event.
		/// </summary>
		/// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
		/// <param name="app">The HttpApplication instance.</param>
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        {
            string currentURL = app.Request.Path.ToLower();

            string PageID = null;
            if (requestedPath.EndsWith(".aspx"))
            {
                if (!System.IO.File.Exists(app.Server.MapPath(currentURL)))
                {

                    foreach (SiteMapNode node in SiteMap.RootNode.GetAllNodes())
                    {

                        if (node.Url.ToLower() == currentURL.Replace("/", ""))
                        {
                            //throw new Exception("ID is null" + node.Key);
                            PageID = node.Key;
                            break;
                        }
                    }

                    if (PageID == null)
                        PageID = Enterprise.Config.GetStartPageID();

                    app.Context.RewritePath(string.Format("default.aspx?PageID={0}", PageID));
                }
            }

            /*
            try
            {
                string url = string.Empty;
                string toUrl = string.Empty;

                if (requestedPath.EndsWith(".aspx"))
                {
                    if (!System.IO.File.Exists(app.Context.Server.MapPath(requestedPath)))
                    {
                        RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

                        for (int i = 0; i < rules.Count; i++)
                        {
                            if (rules[i].LookFor.Contains("~/(*).aspx"))
                            {
                                
                                foreach (SiteUrl surl in GetAllUrls(app))
                                {
                                    if (surl.ConstructUrl().Equals(app.Request.Path.Replace("/", "")))
                                    {
                                        toUrl = string.Format("/?PageID={0}", rules[i].SendTo, surl.ID);
                                        app.Context.RewritePath(toUrl);
                                        break;
                                    }
                                }
                            }
                          
                            
                             
                        }
                    }
                }
                else
                {
                    toUrl = string.Format("/?PageID={0}", Enterprise.Config.GetStartPageID());
                    app.Context.RewritePath(toUrl);
                }
            }
            catch 
            {
                app.Context.Response.Redirect("/ErrorDocs/404.aspx");
            }
            */
        }


        private string ConstructUrl(string s)
        {
            return string.Format("{0}.aspx", s);
        }

        /// <summary>
        /// Creating a list of urls.
        /// </summary>
        /// <param name="app"></param>
        /// <returns>List of SiteUrl's</returns>
        public List<SiteUrl> GetAllUrls(System.Web.HttpApplication app)
        {
            //Cached to minimize database calls
            object o = app.Context.Cache["SITEURLS"];
            if (o == null)
            {
                List<SiteUrl> urls = new List<SiteUrl>();
                SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EPSConnectionString"].ConnectionString);

                SqlCommand command = new SqlCommand("proc_GetSiteMap", Conn);
                command.CommandType = CommandType.StoredProcedure;
                Conn.Open();
                SqlDataReader dr = command.ExecuteReader();
                while (dr.Read())
                {
                    urls.Add(new SiteUrl(dr["id"].ToString(), dr["title"].ToString()));
                }
                app.Context.Cache.Insert("SITEURLS", urls);
                Conn.Close();
            }
            return (List<SiteUrl>)app.Context.Cache["SITEURLS"];
        }
      


        /// <summary>
        /// Helper class :: Temporary holder for an url
        /// </summary>
        public sealed class SiteUrl
        {
            private string _id;
            private string _title;

            public SiteUrl(string id, string title) 
            {
                this._id = id;
                this._title = title;
            }

            public string ID
            {
                get { return _id; }
                set { _id = value; }
            }

            public string Title
            {
                get { return _title; }
                set { _title = value; }
            }

            public string ConstructUrl()
            {
                return string.Format("{0}.aspx", _title);
            }
        }
	}
}
